package util

import (
	"errors"
	"time"

	"gitee.com/shiwjlinux/blog-web/config"
	"github.com/dgrijalva/jwt-go"
	_ "github.com/dgrijalva/jwt-go"
	"github.com/sirupsen/logrus"
)

var jwtKey string = config.Conf.JWT.Key

const TokenExpireDuration = time.Hour * 24

type MyClaims struct {
	Name string
	jwt.StandardClaims
}

func GenerateToken(name string) (string, error) {
	c := MyClaims{
		Name: name,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
			Issuer:    "blockche",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodES256, c)
	return token.SignedString([]byte(jwtKey))
}

func ParseToken(tokenString string) (*MyClaims, error) {
	t, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(t *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil {
		logrus.Errorf("ParseWithClaims error: %v", err)
		return nil, err
	}

	if c, ok := t.Claims.(*MyClaims); ok && t.Valid {
		return c, nil
	}
	return nil, errors.New("invalid token")
}
